//
//  LocationViewController.m
//  NNHealthMall
//
//  Created by 蓓蕾 on 2021/9/2.
//  Copyright © 2021 YY. All rights reserved.
//

#import "LocationViewController.h"
#import "NSString+PinYin.h"
#import "LocationTitlesHeaderView.h"
#import "LocationHeaderView.h"

@interface LocationViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) NSArray *sectionArr;
@property (nonatomic, strong) NSDictionary *cityDic;
@property (nonatomic, strong) NSArray *areaArr;
@property (nonatomic, strong) LocationHeaderView *headerView;
@property (nonatomic, strong) NSString *currentCity;
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation LocationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    NSString *areaPath = [[NSBundle mainBundle] pathForResource:@"CityDicFile.plist" ofType:nil];
    _cityDic = [NSDictionary dictionaryWithContentsOfFile:areaPath];
    NSArray *cityNameArr = [_cityDic allKeys];
    _sectionArr = [cityNameArr arrayWithPinYinFirstLetterFormat];
    
    [self initTableView];
}

-(void)initTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    [_tableView registerClass:[LocationTitlesHeaderView class] forHeaderFooterViewReuseIdentifier:@"LocationTitlesHeaderView"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    HotCityConfig *config = [LocationHeaderView defaultConfig];
    config.itemCount = 4;
    config.itemHeight = 40;
    _headerView = [[LocationHeaderView alloc] initWithReuseIdentifier:@"LocationHeaderView" withConfig:config];
    _headerView.frame = CGRectMake(0, 0, kScreenWidth, 550);
    _tableView.tableHeaderView = _headerView;
    _headerView.areaArr = _cityDic[@"郑州市"];
    _currentCity = @"郑州市";
    NSArray *recentCityArr = [NSArray arrayWithContentsOfFile:ResentVisitCityPath];
    NSMutableArray *locationArr = [NSMutableArray new];
    [locationArr addObjectsFromArray:recentCityArr];
    [locationArr removeObject:_currentCity];
    [locationArr insertObject:_currentCity atIndex:0];
    _headerView.locationArr = [NSArray arrayWithArray:locationArr];
    _headerView.hotCityArr = @[@"北京市", @"上海市", @"深圳市", @"广州市", @"成都市", @"杭州市", @"南京市", @"重庆市"];
//    _headerView.frame = CGRectMake(0, 0, kScreenWidth, [_headerView getMaxViewHeight]);
    _headerView.frame = CGRectMake(0, 0, kScreenWidth, [_headerView getMinViewHeight]);
    [_tableView reloadData];
    MJWeakSelf
    _headerView.SelectAreaBlock = ^(BOOL show) {
        if (show) {
            weakSelf.headerView.frame = CGRectMake(0, 0, kScreenWidth, [weakSelf.headerView getMaxViewHeight]);
        }
        else
        {
            weakSelf.headerView.frame = CGRectMake(0, 0, kScreenWidth, [weakSelf.headerView getMinViewHeight]);
        }
        [weakSelf.tableView reloadData];
    };
    _headerView.CityViewBlock = ^(UIButton * _Nonnull sender, NSString * _Nonnull title) {
        [weakSelf.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
        weakSelf.currentCity = title;
        NSString *cityString = title;
        weakSelf.headerView.locationString = cityString;
        weakSelf.areaArr = weakSelf.cityDic[cityString];
        weakSelf.headerView.areaArr = weakSelf.areaArr;
        if (weakSelf.headerView.show) {
            weakSelf.headerView.frame = CGRectMake(0, 0, kScreenWidth, [weakSelf.headerView getMaxViewHeight]);
            [weakSelf.tableView reloadData];
        }
    };
    
    _headerView.ResultCityBlock = ^(UIButton * _Nonnull sender, NSString * _Nonnull title) {
        [weakSelf saveResentVisitCityFile];
        [weakSelf.navigationController popViewControllerAnimated:YES];
        if (weakSelf.SelectCitySuccessBlock) {
            weakSelf.SelectCitySuccessBlock(title);
        }
    };
}

-(void)saveResentVisitCityFile
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSMutableArray *resentVisitCitys;
    if ([fileManager fileExistsAtPath:ResentVisitCityPath]) {
        resentVisitCitys = [NSMutableArray arrayWithContentsOfFile:ResentVisitCityPath];
    }
    else
    {
        resentVisitCitys = [NSMutableArray new];
    }
    if (![resentVisitCitys containsObject:_currentCity]) {
        if (resentVisitCitys.count < 3) {
            [resentVisitCitys insertObject:_currentCity atIndex:0];
        }
        else
        {
            [resentVisitCitys removeLastObject];
            [resentVisitCitys insertObject:_currentCity atIndex:0];
        }
        if ([resentVisitCitys writeToFile:ResentVisitCityPath atomically:YES]) {
            NSLog(@"文件保存成功");
        }
        else
        {
            NSLog(@"文件保存失败");
        }
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{//返回该tableView有几个部分
    return [_sectionArr count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *dict = _sectionArr[section];
    NSMutableArray *array = dict[@"content"];
    return [array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *dict = _sectionArr[indexPath.section];
    NSMutableArray *array = dict[@"content"];
    cell.textLabel.text = array[indexPath.row];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    NSDictionary *dict = _sectionArr[indexPath.section];
    NSMutableArray *array = dict[@"content"];
    NSString *cityString = array[indexPath.row];
    _headerView.locationString = cityString;
    _currentCity = cityString;
    _areaArr = _cityDic[cityString];
    _headerView.areaArr = _areaArr;
//    _headerView.areaArr = @[];
    if (_headerView.show) {
        _headerView.frame = CGRectMake(0, 0, kScreenWidth, [_headerView getMaxViewHeight]);
        [_tableView reloadData];
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSDictionary *dict = _sectionArr[section];
    NSString *title = dict[@"firstLetter"];
    LocationTitlesHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"LocationTitlesHeaderView"];
    headerView.titleString = title;
    return headerView;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{//右边索引 字节数（如果不实现 就不显示右侧索引）
    NSMutableArray *resultArray = [NSMutableArray array];
    for (NSDictionary *dict in _sectionArr) {
        NSString *title = dict[@"firstLetter"];
        [resultArray addObject:title];
    }
    return resultArray;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{//点击右侧索引表项时调用
    //这里是为了指定索引index对应的是哪个section的，默认的话直接返回index就好。其他需要定制的就针对性处理
    
    //以下e.g.实现了将索引0对应到section 1里。其他的正常对应。
    
    //    if (index == 0) {
    //        return 1;
    //    }
    //    return index;
    NSLog(@"点击了索引");
    NSDictionary *indexDic = _sectionArr[index];
    NSLog(@"点击了索引%@",indexDic[@"firstLetter"]);
//    ShowIndexMessage(indexDic[@"firstLetter"]);
    return index;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
